let {
	list
} = require('./src/mock')
const bodyParser = require('body-parser')
const userList = [{
	user: '张三',
	pwd: '123'
},{
	user: '李四',
	pwd: '123'
},{
	user: '王五',
	pwd: '123'
}]
module.exports = {
	devServer: {
		before(app) {
			app.use(bodyParser.json())
			// 订单列表请求接口
			app.get('/api/order/list', (req, res) => {
				// 获取参数数据
				const {
					state = '全部订单', searchValue = "", date = ['', '']
				} = req.query;

				const filterList = list.filter(v => {
					// 筛选订单状态
					if (state === '全部订单') return true
					return v.state === state
				}).filter((v) => {
					// 模糊搜索
					if (searchValue === '') return true
					// 搜索 id tel 字段
					return v.id.includes(searchValue) || v.tel.toString().includes(searchValue)
				}).filter(v => {
					// 筛选日期
					const [date1, date2] = date;
					if (date1 === '' || date2 === "") return true
					return +new Date(date1) < +new Date(v.createTime) && +new Date(date2) > +new Date(v.createTime)
				})

				// 返回
				res.send({
					code: 200,
					data: filterList
				})
			})

			// 订单删除接口
			app.post('/api/order/list/delete', (req, res) => {
				// 获取删除的id
				const {
					id
				} = req.body;
				// 筛选我们数据 删除
				list = list.filter(v => !id.includes(v.id))
				res.send({
					code: 200,
					message: '删除成功！！'
				})
			})

			// 订单添加接口
			app.post('/api/order/list/add', (req, res) => {
				list.unshift(req.body);
				res.send({
					code: 200,
					message: '数据添加成功！！！'
				})
			})

			// 订单修改接口
			app.post('/api/order/list/edit', (req, res) => {
				const { id } = req.body
				// 通过 id 查找数据
				const item = list.find(v => v.id === id)
				console.log('*****************************************')
				console.log(item, req.body)
				// 修改数据
				Object.assign(item, req.body);
				res.send({
					code: 200,
					message: '修改成功！！！'
				})

			})

			// 用户登录接口
			app.post('/api/user/login', (req, res) => {
				const { user, pwd } = req.body;
				const is = userList.find(v => v.user === user && v.pwd === pwd);
				if(is) {
					res.send({
						code: 200,
						data: {
							token: 'ZZZZZZZZZZZZZZZ',
							username: user
						},
						message: '登录成功'
					})
				} else {
					res.send({
						code: 404,
						data: null,
						message: '登录失败，请重新登录'
					})
				}
			})
		}
	}
}